<template>
  <div class="login-container flex" :style="[container]">
    <div class="left-bg">
      <div class="logo">
        <!-- <img src="~@/assets/login_images/logo.png" /> -->
        <template v-if="systemInfo.LOGIN_IMAGE_BASE64">
          <img :src="systemInfo.LOGIN_IMAGE_BASE64" />
        </template>
        <template v-else>
          <img src="~@/assets/login_images/logo.png" />
        </template>
      </div>
      <div class="left-img-1">
        <img src="~@/assets/login_images/login-left-1.png" />
      </div>
      <div class="info">
        <p>{{ systemInfo.LOGIN_DESC }}</p>
      </div>
    </div>
    <div class="flex-1 flex justify-center items-center relative">
      <div class="login-form relative z-10">
        <!-- 这里输入用户名密码也由后端控制是否展示 -->
        <el-form ref="formRef" label-position="left" :model="form" :rules="rules">
          <div class="versions-tips flex">
            <span class="after"><img src="~@/assets/login_images/ver.png" /></span>
            <div>{{ version }}</div>
          </div>
          <div class="title-tips flex justify-center relative">
            <!-- <img src="~@/assets/login_images/title@2x.png" width="145" /> -->
            {{ translateTitle('Base.login.DAMS统一登录平台') }}
            <!-- 三峡环境 -->
            <!-- {{ loginName }} -->
          </div>
          <div v-if="loginConfig.login_type && loginConfig.login_type.includes('userName')">
            <el-form-item prop="USER_ID">
              <el-input
                v-model.trim="form.USER_ID"
                v-focus
                :placeholder="translateTitle('Base.login.请输入用户名')"
                tabindex="1"
                type="text"
                @keyup.enter="next(0)"
              >
                <template #prefix>
                  <vui-icon class="icon-absolute" icon="user-3-fill" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="passwordRef"
                v-model.trim="form.PASSWORD"
                :placeholder="translateTitle('Base.login.请输入密码')"
                tabindex="2"
                :type="passwordType"
                @keyup.enter="next(1)"
              >
                <!-- @keyup.enter="handleLogin" -->
                <template #prefix>
                  <vui-icon class="icon-absolute" icon="lock-unlock-fill" />
                </template>
                <template v-if="passwordType === 'password'" #suffix>
                  <vui-icon class="show-password icon-absolute" icon="eye-off-line" @click="handlePassword" />
                </template>
                <template v-else #suffix>
                  <vui-icon class="show-password icon-absolute" icon="eye-line" @click="handlePassword" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="VERIFY_CODE">
              <el-input
                v-model.trim="form.VERIFY_CODE"
                :placeholder="translateTitle('Base.login.验证码')"
                tabindex="3"
                type="text"
                @keyup.enter="next(2)"
              >
                <template #prefix>
                  <vui-icon class="icon-absolute" icon="shield-check-fill" />
                </template>
              </el-input>
              <img class="code" :src="codeUrl" @click="getCodeUrl" />
            </el-form-item>
            <el-form-item prop="LANGUAGE_CODE">
              <el-select
                ref="selectRef"
                v-model="form.LANGUAGE_CODE"
                class="w-full"
                default-first-option
                :placeholder="translateTitle('Base.login.选择语言')"
                @change="languageChange"
                @keyup.enter="next(3)"
              >
                <template #prefix>
                  <vui-icon class="icon-absolute" icon="earth-fill" />
                </template>
                <el-option v-for="item in languges" :key="item.LANGUAGE_CODE" :label="item.LANGUAGE_DESC" :value="item.LANGUAGE_CODE" />
              </el-select>
            </el-form-item>
            <el-button class="login-btn" :loading="loading" type="primary" @click="handleLogin">
              {{ translateTitle('Base.login.登录') }}
            </el-button>
          </div>
        </el-form>
        <!-- 其他方式登录 -->
        <div v-if="loginConfig.login_type && loginConfig.login_type.includes('eWechatQrCode')" class="another-way">
          <p v-if="loginConfig.login_type && loginConfig.login_type.includes('userName')" class="text-center my-4 text-gray-500">
            {{ translateTitle('Base.login.其他方式登录') }}
          </p>
          <ul class="flex justify-center">
            <!-- 这里暂时只有一个 但是后端会返回数组吧 需要for循环  -->
            <li v-for="(item, index) in anotherWayList" :key="index" class="flex cursor-pointer items-center" @click="openWxTest">
              <img class="icon" :src="item.logo" :title="translateTitle('Base.login.' + item.title)" />
              <span class="select-none">{{ translateTitle('Base.login.' + item.title) }}</span>
            </li>
          </ul>
        </div>
        <!-- 其他方式登录 -->
      </div>
      <!-- 其他方式登录-二维码 -->
      <VuiModal v-show="showLoginModal" v-model="showLoginModal">
        <template #title>{{ translateTitle('Base.login.企业微信登录') }}</template>
        <div class="layer-modal-body overflow-auto w-[400px] h-[400px] flex items-center justify-center flex-wrap">
          <div class="QR-code-box overflow-hidden">
            <div id="wx_reg" class="flex justify-center" :class="{ blurQRCode: hasOverrdue }"></div>
            <div v-if="hasOverrdue" class="cover-box w-full h-full flex flex-col justify-center">
              <div class="text-center">
                <vui-icon class="refresh-icon mb-8" icon="refresh-line" @click="getQRCode" />
                <p class="cover-text">二维码已过期,点击刷新</p>
              </div>
            </div>
          </div>
          <!-- <div class="text-center text-red-500 w-4/5">
            {{ translateTitle('Base.login.请先将企业微信的userid维护到系统用户信息后') }}
          </div> -->
        </div>
      </VuiModal>
      <!-- 其他方式登录-二维码 -->
      <div class="login-copyright">
        <template v-if="systemInfo.COPYRIGHT">{{ systemInfo.COPYRIGHT }}</template>
        <template v-else>Copyright ©2022 中集创见(成都)科技有限公司</template>
      </div>
    </div>
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import { Mixin } from '@/common/minxin/Mixin'
  import { translateTitle } from '@/utils/i18n'
  import { isPassword } from '@/utils/validate'
  // import { updateURLParameter } from '@/utils/tools'
  import { GFCD } from '@/utils/utils'
  import { toAppsPage } from '@project/config'
  import { getLanguges } from '@commonProject/api/user'
  import request from '@/utils/request'
  import i18n from '@commonProject/i18n'
  import dayjs from 'dayjs'
  import canvasFP from '@/utils/canvasFP.js'
  import { v4 as uuidv4 } from 'uuid'
  export default defineComponent({
    name: 'Login',
    components: {
      // Vcode,
    },
    directives: {
      focus: {
        inserted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    mixins: [Mixin],
    data() {
      return {
        formRef: null,
        form: {
          USER_ID: '',
          PASSWORD: '',
          LANGUAGE_CODE: 'zh_CN',
          VERIFY_CODE: '',
          LOGIN_ENTRANCE: 'PC',
        },
        // 其他登录方式的列表
        anotherWayList: [
          {
            title: translateTitle('Base.login.企业微信'),
            type: 'wecom',
            logo: require('@/assets/login_images/wecom.png'),
          },
        ],
        rules: {
          USER_ID: [
            {
              required: true,
              trigger: 'blur',
              validator: (rule, value, callback) => {
                if ('' === value) callback(new Error(translateTitle('Base.login.用户名不能为空')))
                else callback()
              },
            },
          ],
          PASSWORD: [
            {
              required: true,
              trigger: 'blur',
              validator: (rule, value, callback) => {
                if (!isPassword(value)) callback(new Error(translateTitle('Base.login.密码不能少于6位')))
                else callback()
              },
            },
          ],
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        verification: false,
        codeUrl: '',
        languges: [],
        container: {
          width: '100%',
          height: '100%',
        },
        systemInfo: {},
        //其他方式登录
        showLoginModal: false,
        loginConfig: {},
        verification_code_uuid: '',
        overdueTimer: null,
        hasOverrdue: false,
        version: '',
        loginName: '',
      }
    },
    created() {
      this.loading = false
      this.title = this.$store.getters['settings/title']
      this.getLangugesReq()
      this.getCodeUrl()
      this.getAppInfo()
      this.getLoginConfig()
      this.container.width = document.documentElement.clientWidth + 'px'
      this.container.height = document.documentElement.clientHeight + 'px'
      this.version = GFCD('login', 'version')
      // this.loginName = GFCD('login', 'loginName')//三峡环境
    },
    beforeUnmount() {
      this.overdueTimer = null
    },
    methods: {
      translateTitle,
      next() {
        let open = true
        for (let index = 0; index < 4; index++) {
          if (!this.$refs['formRef'].$el[index].value) {
            this.$refs['formRef'].$el[index].focus()
          }
        }
        for (const key in this.form) {
          const element = this.form[key]
          if (!element) {
            open = false
          }
        }
        if (open) {
          this.handleLogin()
        }
      },
      getAppInfo() {
        let method = 'dams.app.info.query'
        request({
          url: GFCD('login', 'domain') + GFCD('login', 'baseUrl'),
          method: 'post',
          data: {
            data: JSON.stringify({ '#LIMIT#': '1', '#PAGE_SIZE#': '10' }),
            method: method,
          },
          notOpenMessage: true,
          baseMessage: true,
        }).then((res) => {
          if (res.code == '00000' && res.data && res.data[method]) {
            let data = res.data[method].data
            if (data.length > 0) {
              this.systemInfo = data[0]
            }
          }
        })
      },
      // 获取登录页的表单和其他方式登录相关配置
      async getLoginConfig() {
        let domain = process.env.NODE_ENV === 'development' ? GFCD('login', 'domain').split('//')[1] : window.location.host
        let res = await request({
          url: GFCD('login', 'domain') + GFCD('login', 'baseUrl'),
          method: 'post',
          data: {
            data: JSON.stringify({ requestDomainNameOrIp: domain }),
            method: 'sysUserServiceImpl.getLoginParameters',
          },
          notOpenMessage: true,
          baseMessage: true,
        })
        this.loginConfig = res.data
        this.loginConfig.login_type = res.data.login_type.split(';')
      },
      getCodeUrl() {
        this.changeCode()
      },
      async getLangugesReq() {
        const data = await getLanguges()
        if (data) {
          this.languges = data.data['dams.language.query'].data
        }
      },
      languageChange(language) {
        this.$store.dispatch('user/setLanguage', language)
        i18n.global.locale = language
      },
      handlePassword() {
        this.passwordType === 'password' ? (this.passwordType = '') : (this.passwordType = 'password')
      },
      async login(params) {
        console.log('params', params)
        return this.$store.dispatch('user/login', params)
      },
      handleLogin() {
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            try {
              this.loading = true
              console.log('params', this.form)
              let fingerprint = `${canvasFP({ uid: this.form.USER_ID || '' }, true).hash}`
              this.$store.dispatch('tmp/setFingerprint', fingerprint)
              let domain = process.env.NODE_ENV === 'development' ? GFCD('login', 'domain').split('//')[1] : window.location.host
              this.login({
                ...this.form,
                requestDomainNameOrIp: domain,
                'FINGER-MARK': fingerprint,
                verification_code_uuid: this.verification_code_uuid,
              })
                .then(() => {
                  if (toAppsPage) {
                    this.$router.push('/apps')
                    const Steve = new BroadcastChannel('Avengers')
                    Steve.postMessage('Assemble!')
                  } else {
                    this.$router.push('/')
                  }
                })
                .catch(() => {
                  this.getCodeUrl()
                })
              // to apps page
            } finally {
              this.loading = false
            }
          } else {
            console.log(valid)
          }
        })
      },
      async changeCode() {
        this.verification_code_uuid = uuidv4()
        // let verifyCode = GFCD('login', 'domain') + GFCD('login', 'baseUrl') + '?method=sysUserServiceImpl.verifyCode'
        // let _url = updateURLParameter(verifyCode, 'verification_code_uuid', `${this.verification_code_uuid}`)
        // this.codeUrl = _url

        let res = await request({
          url: GFCD('login', 'domain') + GFCD('login', 'baseUrl'),
          method: 'post',
          data: {
            data: JSON.stringify({
              verification_code_uuid: `${this.verification_code_uuid}`,
            }),
            method: 'sysUserServiceImpl.verifyCode',
          },
          // responseType: 'blob',
          // notOpenMessage: true,
          // baseMessage: true,
        })
        console.log(res.data.verifyCode)
        // this.codeUrl = window.URL.createObjectURL(res)
        this.codeUrl = res.data.verifyCode
      },
      //其他方式登录
      openWxTest() {
        this.showLoginModal = true
        //弹出时存语言
        this.getQRCode()
      },
      getQRCode() {
        console.warn('%c 获取二维码', 'color: red;')
        let _loginUrl = `${location.href.split('#')[0]}/#/otherLoginRedirect`
        // eslint-disable-next-line no-undef
        var wwLogin = new WwLogin({
          id: 'wx_reg',
          appid: this.loginConfig.Enterprise_WeChat_APPID,
          agentid: this.loginConfig.Enterprise_WeChat_AgentId,
          redirect_uri: encodeURIComponent(_loginUrl),
          state: dayjs().valueOf(),
          lang: 'zh',
        })
        this.hasOverrdue = false
        clearTimeout(this.overdueTimer)

        let timer = setTimeout(() => {
          clearTimeout(timer)
          console.warn('%c start timer', 'color: red;')
          this.overdueTimer = setTimeout(() => {
            clearTimeout(this.overdueTimer)
            console.warn('%c timeout', 'color: red;')
            this.hasOverrdue = true
          }, 15000)
        }, 2000)
        console.log('wwLogin', wwLogin)
      },
    },
  })
</script>

<style lang="scss" scoped>
  .login-container {
    // height: 100vh;
    // background: url('~@/assets/login_images/background.png') center center fixed no-repeat;
    // background-size: cover;
    overflow: hidden;
    background-color: #f5f7fd;
  }
  .left-bg {
    width: 55%;
    height: 100%;
    display: block;
    background-image: url('~@/assets/login_images/login-left-image.png');
    background-size: cover;
    .logo {
      width: 300px;
      padding: 20px 0 0 20px;
      height: 100px;
      overflow: hidden;
    }
    .left-img-1 {
      width: 80%;
      text-align: center;
      margin-top: 4%;
      img {
        width: 75%;
        display: inline-block;
      }
    }
    .info {
      text-align: center;
      width: 80%;
      margin-top: 5%;
      p {
        width: 75%;
        color: #fff;
        font-size: 16px;
        font-weight: 400;
        text-align: left;
        display: inline-block;
        line-height: 26px;
      }
    }
  }
  .login-form {
    background-color: #fff;
    position: relative;
    width: 400px;
    padding: 40px 40px 30px 40px;
    overflow: hidden;
    background-size: 100% 100%;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    overflow: hidden;
    .title {
      font-size: 54px;
      font-weight: 500;
      color: var(--el-color-white);
    }
    .title-tips {
      margin: 30px 0 44px 0;
      color: #1e52c9;
      font-size: 24px;
      font-weight: 700;
      text-align: center;
    }
    .versions-tips {
      position: absolute;
      right: 0;
      top: 0;
      .after {
        display: block;
        height: 23px;
        img {
          height: 100%;
        }
      }
      div {
        background: linear-gradient(180deg, #fcebbc 1%, #f5cd98);
        padding: 5px;
        color: #754c1e;
        font-size: 11px;
      }
    }

    .login-btn {
      display: inherit;
      width: 100%;
      height: 40px;
      margin-top: 5px;
      border: 0;
      border-radius: 40px;
      background-color: #1e52c9;

      &:hover {
        opacity: 0.9;
      }

      .forget-passwordword {
        width: 100%;
        margin-top: 40px;
        text-align: left;

        .forget-password {
          width: 129px;
          height: 19px;
          font-size: 20px;
          font-weight: 400;
          color: rgba(92, 102, 240, 1);
        }
      }
    }

    .tips {
      margin-bottom: 10px;
      font-size: $base-font-size-default;
      color: var(--el-color-white);

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .title-container {
      position: relative;

      .title {
        margin: 0 auto 40px auto;
        font-size: 34px;
        font-weight: bold;
        color: var(--el-color-primary);
        text-align: center;
      }
    }

    i.icon-absolute {
      position: absolute;
      top: 4px;
      left: 5px;
      z-index: $base-z-index;
      font-size: 16px;
      color: #dddfe6;
      cursor: pointer;
      user-select: none;
    }

    i.show-password {
      position: absolute;
      right: 25px;
      left: -20px;
      font-size: 16px;
      color: #d7dee3;
      cursor: pointer;
      user-select: none;
    }

    :deep() {
      .el-form-item {
        padding-right: 0;
        margin: 20px 0 22px 0;
        color: #454545;
        background: transparent;
        border: 1px solid transparent;

        &__content {
          min-height: $base-input-height;
          line-height: $base-input-height;
        }

        &__error {
          position: absolute;
          top: 100%;
          left: 18px;
          font-size: $base-font-size-small;
          line-height: 18px;
          color: var(--el-color-error);
        }
      }

      .el-input {
        box-sizing: border-box;

        input {
          height: 36px;
          padding-left: 35px;
          font-size: $base-font-size-default;
          line-height: 44px;
          border-radius: 40px;
          font-size: 12px;
          color: #999;
        }
      }

      .code {
        position: absolute;
        top: 4px;
        right: 12px;
        cursor: pointer;
        border-radius: $base-border-radius;
        height: 28px;
      }
    }
  }
  .login-copyright {
    text-align: center;
    font-weight: 400;
    color: #8a8bb1;
    font-size: 12px;
    position: absolute;
    bottom: 2px;
    width: 100%;
  }
  .another-way {
    user-select: none;
    .icon {
      width: 35px;
    }
  }
  @keyframes rotate {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
  .blurQRCode {
    filter: blur(10px);
  }
  .QR-code-box {
    position: relative;
    width: 300px;
    height: 400px;
    .cover-box {
      position: absolute;
      width: 280px;
      height: 280px;
      left: 0;
      top: 0;
      width: inherit;
      height: inherit;
      background-color: #2d2d2db0;
      overflow: hidden;
      .refresh-icon {
        border-radius: 50%;
        background-color: #fff;
        height: 40px;
        width: 40px;
        box-shadow: 0 0 11px 2px #00000045;
        line-height: 40px;
        font-size: 21px;
        &:hover {
          cursor: pointer;
          animation: rotate 2s linear infinite;
        }
      }
      .cover-text {
        color: #fff;
        font-size: 17px;
      }
    }
  }
</style>
